var geocoder;
var map;
var bounds;

var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

var calleOrigen;
var calleDestino;

var autosInfo;
var posAutos = [];

var minTime=99999999;
var minTimeText;
var idchoferSeleccionado;
var indexSeleccionado;

function obtenerChofer() {
	
	if(validarDatos()) {

//	codeAddress('florida 200, caba, buenos aires');
	
	
	//var origin1 = new google.maps.LatLng(55.930385, -3.118425);
	calleOrigen = [$('#calleOrig').val() + ' ' + $('#alturaOrig').val() + ', caba, buenos aires'];
	calleDestino = [$('#calleDest').val() + ' ' + $('#alturaDest').val() + ', caba, buenos aires'];
	
	loadAutos(false);
	
	markDestinos(calleOrigen[0], calleDestino[0]);
	
	}
	else {
		$('#outputDiv')[0].innerHTML = 'Datos invalidos para realizar el pedido.';
	}
	
	
	// distanceMatrix(calleOrigen, calleDestino);
}

function loadAutos(esReasignacion) {
	jQuery.ajax({											
		url: 'cliente?action=obtenerAutos&reasignar='+esReasignacion+'&idchoferactual='+ $('#idchoferactual').val()+'&barrioOrig='+ $('#barrioOrig').val()+'&barrioDest='+ $('#barrioDest').val(),
		dataType: 'json',
		success: function(data) {

					if(data.length==0) {
						document.getElementById('outputDiv').innerHTML = 'No hay choferes disponibles en este momento.';
						return;
					}
			
					autosInfo = data;
					
					for(var i=0;i<data.length;i++){
				        var obj = data[i];
				        posAutos[i] = new google.maps.LatLng(obj.latitud, obj.longitud);
				    }
					
					if(!esReasignacion)
						distanceMatrix(posAutos, calleOrigen, callback);
					else 
						distanceMatrix(posAutos, calleOrigen, callbackReasignacion);
				}										
	});
}

function distanceMatrix(origin, destination, callbackFunction) {
	
	var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: origin,
        destinations: destination,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, callbackFunction);
}

function callback(response, status) {
	
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } 
    else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('outputDiv');
      outputDiv.innerHTML = '';
      

      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
       
        for (var j = 0; j < results.length; j++) {
          
          outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
              + ': ' + results[j].distance.text + ' in '
              + results[j].duration.text + '<br>';
          
          // guardar el chofer mas cercano a la posicion del pasajero
          if(results[j].duration.value < minTime) {
        	  minTime = results[j].duration.value;
        	  minTimeText = results[j].duration.text;
        	  idchoferSeleccionado = autosInfo[i].id;
        	  indexSeleccionado = i;
          }
        }
      }
      
//      outputDiv.innerHTML += '<br>Min time: '+ minTime +', chofer id: '+ idchoferSeleccionado;
      outputDiv.innerHTML += '<br>Su chofer asignado es: '+autosInfo[indexSeleccionado].chofer+'  <br> Tiempo estimado de arribo: '+minTimeText;
      
      confirmarViaje();
      
      // mostrar mapa
//      $('#map').show();
      
      // borrar variables aux
      minTime = 99999999;
      idchoferSeleccionado=-1;
      indexSeleccionado=-1;
    }
}

function confirmarViaje() {
	
	jQuery.ajax({											
		url: 'cliente?action=nuevoViaje&idchofer='+idchoferSeleccionado+
									  '&pasajero='+$('#pasajero').val()+
									  '&calleOrig='+$('#calleOrig').val()+
									  '&alturaOrig='+$('#alturaOrig').val()+
									  '&calleDest='+$('#calleDest').val()+
									  '&alturaDest='+$('#alturaDest').val()+
									  '&barrioOrig='+$('#barrioOrig').val()+
									  '&barrioDest='+$('#barrioDest').val(),
		dataType: 'json',
		success: function(data) {
			
				}										
	});
}

function markDestinos(origen, destino) {
	
	bounds = new google.maps.LatLngBounds();
	
	$('#map').show();
	
	
	addMarker(origen, false);
	addMarker(destino, true);
	
}


function validarDatos() {
	
	if($('#pasajero').val() =='' ||
	   $('#calleOrig').val()=='' || $('#alturaOrig').val()=='' || 
	   $('#calleDest').val()=='' || $('#alturaDest').val()=='') {
		return false;
	}
	
	return true;
}



//--- Reasignar viaje ---//

function reasignarViaje() {
	
	calleOrigen = [$('#calleOrigen').val() + ', caba, buenos aires'];
	
	loadAutos(true);
}

function confirmarReasignacion() {
	
	jQuery.ajax({											
		url: 'cliente?action=reasignarViaje&idchofer='+idchoferSeleccionado+
									  	  '&idviaje='+$('#idviaje').val(),
		dataType: 'json',
		success: function(data) {
			
				}										
	});
}

function callbackReasignacion(response, status) {
	
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } 
    else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('outputDiv');
      outputDiv.innerHTML = '';
      

      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
       
        for (var j = 0; j < results.length; j++) {
          
          outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
              + ': ' + results[j].distance.text + ' in '
              + results[j].duration.text + '<br>';
          
          // guardar el chofer mas cercano a la posicion del pasajero
          if(results[j].duration.value < minTime) {
        	  minTime = results[j].duration.value;
        	  minTimeText = results[j].duration.text;
        	  idchoferSeleccionado = autosInfo[i].id;
        	  indexSeleccionado = i;
          }
        }
      }
      
//      outputDiv.innerHTML += '<br>Min time: '+ minTime +', chofer id: '+ idchoferSeleccionado;
      outputDiv.innerHTML += '<br>Su chofer asignado es: '+autosInfo[indexSeleccionado].chofer+'  <br> Tiempo estimado de arribo: '+minTimeText;
      
      confirmarReasignacion();
      
      // mostrar mapa
//      $('#map').show();
      
      // borrar variables aux
      minTime = 99999999;
      idchoferSeleccionado=-1;
      indexSeleccionado=-1;
    }
}


//--- Funciones generales ---//

function addMarker(location, isDestination) {
    
	var icon;
    if (isDestination) {
      icon = destinationIcon;
    } else {
      icon = originIcon;
    }
    
    geocoder.geocode({'address': location}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        bounds.extend(results[0].geometry.location);
        map.fitBounds(bounds);
        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          icon: icon
        });
//        markersArray.push(marker);
      } else {
        alert('Geocode was not successful for the following reason: '
          + status);
      }
    });
}

function codeAddress(address) {
    
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        alert(results[0].geometry.location);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
}